<template>
  <div class="common_width dm_myOrder">
    <TableTitle title="我的订单">
      <div>
        （当前共有 <i>{{ totalNum }}</i> 笔订单）
      </div>
    </TableTitle>
    <el-table
      border
      style="width: 100%"
      size="small"
      :class="`dm_myOrder__title${totalNum ? ' hidden' : ''}`"
    >
      <el-table-column
        v-for="c in columns"
        :key="c.id"
        :prop="c.prop"
        :label="c.label"
        :width="c.width"
        align="center"
      ></el-table-column>

      <el-table-column prop="operation" label="操作" width="140" align="center">
      </el-table-column>
    </el-table>

    <div
      v-for="(tb, index) in tableData"
      :key="tb.id"
      class="dm_myOrder__content"
    >
      <el-row class="t_header">
        <el-col :span="6">{{ tb.createTime }}</el-col>
        <el-col :span="6">订单号： {{ tb.orderSn }}</el-col>
        <el-col :span="6">订单状态： {{ tb.status }}</el-col>
        <el-col :span="6">
          <span @click="cancelCartClick(tb.id)" v-if="tb.status === '待付款'"
            >取消订单</span
          >
          <span @click="deleteCartClick(tb.id)" v-if="tb.status !== '待发货' && tb.status !== '已发货' && tb.status !== '待付款'">删除</span>
        </el-col>
      </el-row>
      <el-table
        :data="tb.orderItemList"
        border
        style="width: 100%"
        size="small"
        :show-header="false"
      >
        <el-table-column
          v-for="c in columns"
          :key="c.id"
          :prop="c.prop"
          :label="c.label"
          :width="c.width"
          align="center"
        >
          <template slot-scope="scope">
            <img
              v-if="c.prop == 'mainPicture'"
              style="width: 100%"
              :src="scope.row.productPic"
            />
            <router-link
              v-if="c.prop == 'description'"
              class="title_style"
              :to="{ name: 'detail', query: { id: scope.row.productId } }"
            >
              <span :title="scope.row.productSubTitle">{{
                scope.row.productName
              }}</span>
              <span class="ellipsis">规格：{{ scope.row.productAttr }}</span>
            </router-link>
            <span v-if="c.prop == 'price' || c.prop == 'totalprice'"
              >￥{{
                c.prop == "price"
                  ? scope.row["productPrice"]
                  : c.prop == "totalprice"
                  ? parseFloat(scope.row["productPrice"]) *
                    scope.row["productQuantity"]
                  : 0 | keepTwoDecimalPlaces
              }}</span
            >
            <span v-if="c.prop == 'num'">x{{ scope.row.productQuantity }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="operation"
          label="操作"
          width="140"
          align="center"
        >
          <template>
            <div class="operation">
              <span @click="goNextPage('comment', tb.id, index)" v-if="tb.status === '已完成'">评价</span>
              <span @click="goNextPage('detail', tb.id)">订单详情</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-pagination
      background
      layout="prev, pager, next"
      :total="totalNum"
      :page-size="pageSize"
      :current-page="pageNum"
      @current-change="handlePageChange"
    >
    </el-pagination>
  </div>
</template>

<script>
import tableTitle from "@/components/tableTitle/index.vue";
import {
  getAllOrderData,
  postDeleteOrderData,
  postCancelOrderData
} from "@/api/myOrder";
import { formatSpecs } from "@/utils/format";
export default {
  data() {
    return {
      columns: [
        { id: 1, prop: "mainPicture", label: "主图", width: 107 },
        { id: 2, prop: "description", label: "商品详情" },
        { id: 3, prop: "price", label: "单价", width: 162 },
        { id: 4, prop: "num", label: "数量", width: 107 },
        { id: 5, prop: "totalprice", label: "小计", width: 172 }
      ],
      tableData: [],
      pageNum: 1,
      pageSize: 5,
      status: -1,
      totalNum: 0
    };
  },
  mounted() {
    this.getAllOrderData();
  },
  methods: {
    // 进入 评价/订单详情
    goNextPage(_this, orderId, index) {
      let obj = {
        comment: () => {
          this.$router.push({
            name: "myComment",
            query: { orderId, oIndex: index }
          });
        },
        detail: () => {
          this.$router.push({ name: "orderDetails", query: { orderId } });
        }
      };
      obj[_this]();
    },
    // 删除 - 操作
    deleteCartClick(orderId) {
      this.$confirm("确认删除这笔订单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.postDeleteOrderData({ orderId });
        })
        .catch(() => {
          return;
        });
    },
    // 取消 - 操作
    cancelCartClick(orderId) {
      this.$confirm("确认取消这笔订单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.postCancelOrderData({ orderId });
        })
        .catch(() => {
          return;
        });
    },
    // 查询我的订单
    async getAllOrderData() {
      const res = await getAllOrderData({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        status: this.status
      });
      try {
        if (res.code === 200) {
          const data = res.data || {};
          data.list.forEach(element => {
            element.orderItemList.forEach(item => {
              item.productAttr = formatSpecs(item.productAttr);
            });
            if (element.status === 0) {
              element.status = "待付款";
            } else if (element.status === 1) {
              element.status = "待发货";
            } else if (element.status === 2) {
              element.status = "已发货";
            } else if (element.status === 3) {
              element.status = "已完成";
            } else if (element.status === 4) {
              element.status = "已关闭";
            } else if (element.status === 5) {
              element.status = "无效订单";
            }
          });
          this.totalNum = data.total;
          this.tableData = data.list;
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 删除
    async postDeleteOrderData(params = {}) {
      const res = await postDeleteOrderData(params);
      try {
        if (res.code === 200) {
          this.getAllOrderData();
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 取消订单
    async postCancelOrderData(params = {}) {
      const res = await postCancelOrderData(params);
      try {
        if (res.code === 200) {
          this.getAllOrderData();
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 分页处理
    async handlePageChange(val) {
      this.pageNum = val;
      this.getAllOrderData();
    }
  }
};
</script>

<style lang="scss">
@import "@/assets/css/myOrder/index.scss";
</style>
